package cn.com.service.impl;

import cn.com.Util.DateUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import cn.com.domain.FilesEntity;
import cn.com.mapper.FilesMapper;
import cn.com.service.FilesService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
import java.util.Random;

/**
 * @Author CRL
 * @Date 2021/4/18 23:40
 */
@Service
public class FilesServiceImpl extends ServiceImpl<FilesMapper, FilesEntity> implements FilesService {

    @Autowired
    FilesService filesService;
    @Value("${file.attachRootPath}")
    private String attachRootPath;
    @Value("${file.url}")
    public String fileUrl;

    /**
     * 上传文件接口
     *
     * @param request request
     * @return return
     */
    @Override
    public FilesEntity upload(HttpServletRequest request) {
        FilesEntity files = new FilesEntity();
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            Object[] fileKeys = fileMap.keySet().toArray();
            MultipartFile multipartFile = fileMap.get(fileKeys[0]);
            //文件大小，字节,90.2 KB (92,422 字节)
            long size = multipartFile.getSize();
            String filesize;
            double size2;
            if (size / (1024 * 1024 * 1024) > 1) {
                //单位G
                size2 = new BigDecimal((float) size / (1024 * 1024 * 1024)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                filesize = size2 + "G";
            } else if (size / (1024 * 1024) > 1) {
                //单位M
                size2 = new BigDecimal((float) size / (1024 * 1024)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                filesize = size2 + "M";
            } else {
                //单位KB
                size2 = new BigDecimal((float) size / (1024)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                filesize = size2 + "KB";
            }
            String timeUrl = DateUtils.getYear() + DateUtils.getMonth() + DateUtils.getDay();
            //文件名
            String filename = multipartFile.getOriginalFilename();
            String[] name = filename.split("\\.");
            //文件扩展名
            String suffix = name[name.length - 1];
            //文件类型
            String filetype = request.getParameter("filetype");
            String filename2 = System.currentTimeMillis() + "_" + new Random().nextInt(9999) + "." + name[name.length - 1];
            String filePath = attachRootPath + '/' + timeUrl + '/';
            File newFile = new File(filePath, filename2);
            //判断路径是否存在，如果不存在就创建一个
            if (!newFile.getParentFile().exists()) {
                newFile.getParentFile().mkdirs();
            }
            multipartFile.transferTo(newFile);
            //保留文件本地路径
            String filepath = "/download/" + timeUrl + '/' + filename2;
            files.setFilesize(filesize);
            files.setFilepath(filepath);
            files.setFilename(filename);
            files.setFilename2(filename2);
            files.setSuffix(suffix);
            files.setFiletype(filetype == null ? "0" : filetype);
            files.setCreateTime(new Date());
            files.setUpdateTime(new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
        boolean save = filesService.save(files);
        if (save) {
            return files;
        } else {
            return null;
        }
    }

    @Override
    public void download(HttpServletResponse response, String filePath, String fileType, String fileName) throws IOException {
        File file = new File(filePath);
        long fileLength = file.length();

        if (fileType.equals("txt")) {
            response.setContentType("text/plain;");
            response.setHeader("Content-disposition", "attachment; filename=" + new String((fileName).getBytes("GBK"), "ISO8859-1"));

        } else if (fileType.equals("doc")) {
            response.setContentType("application/msword;");
            response.setHeader("Content-disposition", "attachment; filename=" + new String((fileName).getBytes("GBK"), "ISO8859-1"));

        } else if (fileType.equals("xls")) {
            response.setContentType("application/ms-excel;");
            response.setHeader("Content-disposition", "attachment; filename=" + new String((fileName).getBytes("GBK"), "ISO8859-1"));

        } else if (fileType.equals("pdf")) {
            response.setContentType("application/pdf;");
            response.setHeader("Content-disposition", "attachment; filename=" + new String((fileName).getBytes("GBK"), "ISO8859-1"));

        } else if (fileType.equals("jpg") || fileType.equals("jpeg") || fileType.equals("png")) {
            response.setContentType("image/jpeg");
            response.setHeader("Content-Length", "" + fileLength);
        } else if (fileType.equals("amr")) {
            response.setContentType("audio/amr-wb");
            response.setHeader("Content-disposition", "attachment; filename=" + new String((fileName).getBytes("GBK"), "ISO8859-1"));

        } else {
            response.setContentType("application/x-msdownload;");
            response.setHeader("Content-disposition", "attachment; filename=" + new String((fileName).getBytes("GBK"), "ISO8859-1"));

        }
        InputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(filePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        bos = new BufferedOutputStream(response.getOutputStream());
        byte[] buff = new byte[2048];
        int bytesRead;
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }
        if (bis != null) {
            bis.close();
        }
        if (bos != null) {
            bos.flush();
            bos.close();
        }
    }

}